package com.mzw.huaxiarealestatebackend.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.util.StrUtil;

import com.mzw.huaxiarealestatebackend.common.utils.DataResult;
import com.mzw.huaxiarealestatebackend.common.utils.DateFormat;
import com.mzw.huaxiarealestatebackend.common.utils.VerificationCodeUtils;
import com.mzw.huaxiarealestatebackend.dao.UserDao;
import com.mzw.huaxiarealestatebackend.entity.MailRequest;
import com.mzw.huaxiarealestatebackend.entity.User;
import com.mzw.huaxiarealestatebackend.service.SendMailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.mzw.huaxiarealestatebackend.constants.RedisConstants.REGISTER_V_CODE;


@Api(tags = "用户注册")
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class RegisterController {

    @Autowired
    private UserDao userMapper;

    @Value("${mzw.password-key}")
    private String passwordKey;

    @Autowired
    private SendMailService sendMailService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 注册
     * @param user
     * @return
     */
    @ApiOperation("用户注册(默认权限为普通用户)")
    @PostMapping("/register")
    @Transactional // 涉及到两张表的操作 => 开启事务
    public DataResult register(@RequestBody User user) {
        if (!Objects.isNull(userMapper.selectUserInfoOne(user.getUserEmail()))) {
            return DataResult.failure("该邮箱已存在");
        } else {
            // 加密存储
            user.setUserPassword(SaSecureUtil.aesEncrypt(passwordKey, user.getUserPassword()));
            user.setRegisterTime(DateFormat.getNowDateFormat());
            // 默认为普通用户
            user.setUserRole("user");
            // 新增用户信息
            int count = userMapper.insertUserInfo(user);
            // 定制信息
            String msg = count  > 0 ? "注册成功" : "注册失败";
            return DataResult.ok(msg);
        }
    }

    /**
     * 发送注册邮件
     * @param email
     * @return
     */
    @ApiOperation("发送注册邮件")
    @PostMapping("/simple/{email}")
    public DataResult SendVerificationCodeMessage(@PathVariable String email) {
        String verification6Code = VerificationCodeUtils.getVerification6Code();
        MailRequest mailRequest = new MailRequest();
        mailRequest.setSubject("【华夏房产】");
        mailRequest.setSendTo(email);
        // 存入Redis设置5分钟之后过期
        String key = REGISTER_V_CODE + email;
        stringRedisTemplate.opsForValue().set(key, verification6Code, 5, TimeUnit.MINUTES);
        mailRequest.setText("【华夏房产】，尊敬的华夏房产用户，您正在注册，您的验证码为: " + verification6Code + "，该验证码5分钟内有效，请勿泄露他人。");
        mailRequest.setFrom("yunlu29817@163.com" + "(华夏房产)");
        sendMailService.sendSimpleMail(mailRequest);
        return DataResult.ok("邮件发送成功");
    }

    /**
     * 对验证码进行验证
     * @param email
     * @param code
     * @return
     */
    @ApiOperation("验证邮箱验证码")
    @PostMapping("/verification/{email}/{code}")
    public DataResult verification(@PathVariable String email, @PathVariable String code) {
        String key = REGISTER_V_CODE + email;
        // 从Redis中获取验证码
        String codeCache = String.valueOf(stringRedisTemplate.opsForValue().get(key));
        System.out.println("codeCache" + codeCache);
        // 验证码为空返回失败结果
        if (codeCache == null || "".equals(codeCache)) {
            return DataResult.failure();
        }
        if (StrUtil.equals(codeCache, code)) {
            // 验证成功后直接删除缓存 并返回状态码200给前端
            stringRedisTemplate.delete(key);
            return DataResult.ok("验证成功");
        } else {
            return DataResult.failure("验证码错误，请输入正确的验证码");
        }
    }
}

